package postAPI

import (
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"go-gin-init/app/models/req"
	"go-gin-init/app/models/resp"
	"go-gin-init/app/service"
	"go-gin-init/common/result"
	"go-gin-init/common/tool"
	"go-gin-init/common/xerr"
)

// PostPageList
// @Summary 帖子列表
// @Description
// @Tags POST
// @Accept json
// @Produce json
// @Param Param body req.PageListReq true "请求参数"
// @Success 200 {object} result.JsonResult "{"code":200,"data":{},"msg":"SUCCESS"}"
// @Failure 400 {object} result.JsonResult "{"code":200,"data":{},"msg":""}"
// @Failure 500 {string} string "Internal Server Error"
// @Router /post/list [post]
func PostPageList(c *gin.Context) {

	var u req.PageListReq
	if err := c.ShouldBind(&u); err != nil {
		result.ParamErrorResult(c, err)
		return
	}

	defaultPostModel := service.NewDefaultPostModel()
	defaultUserModel := service.NewDefaultUserModel()

	list, err := defaultPostModel.FindListPage(u.SearchText, u.PageNum, u.PageSize)
	if err != nil {
		result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		return
	}
	var count int64 = 0
	var postPageList []*resp.PostResp

	for _, post := range list {

		temp := resp.PostResp{}
		copier.Copy(&temp, post)
		temp.Tags = tool.String2array(post.Tags)

		user, err := defaultUserModel.FindById(post.AuthorId)
		if err != nil && err != service.ErrNotFound {
			result.JsonRsp(c, nil, xerr.NewErrCode(xerr.SERVER_COMMON_ERROR))
		}

		if user != nil {
			temp.UserName = user.UserName
		}

		postPageList = append(postPageList, &temp)
		count++

	}

	result.JsonRsp(c, resp.PageListResp{
		Count: count,
		Data:  postPageList,
	}, nil)

}
